﻿/*------------------------公用textarea maxlength插件利用方法-------------------------*/
//自动验证输入字符表单的长度
;
(function($) {
    jQuery.fn.checkFieldLength = function(options) {
        options = $.extend({
            onlyNum:true,
            fontCls:"f_red",
            wordCount:"#J_uc_count",
            isNeedAnim:true
        }, options || {});

        return this.each( function() {          
            var field = $(this);
	   /*
            if (field.data('bindCheckFieldLength') == true) {
                return true;
            }
          */
            var maxlen = options.maxlength || parseInt(field.attr('maxlength'), 10);
            var tm = null;
            var _isFirst=true;
            if(options.isNeedAnim){
                 $(options.wordCount).hide();
            }
            var checkLength = function() {
                if(_isFirst&&options.isNeedAnim){
                    $(options.wordCount).fadeIn();
                    _isFirst=false;
                }
                var text = field.val();
                if (field.data('oldtext') == text) {
                    clearInterval(tm);
                    tm = null;
                } else {
                    field.data('oldtext', text);
                }

                if ($.isFunction(options.check)) {
                    text = options.check(text);
                }
                text = text.slice(0, maxlen);
                if (text != field.val()) {
                    field.val(text);
                }
                var $_allowText="<span class='red_a f_b'>"+Math.max(0, maxlen - text.length)+"</span>/"+maxlen;
                if(options.onlyNum) {
                    (options.wordCount && $(options.wordCount).eq(0).html($_allowText));
                } else {
                    $(options.wordCount).eq(0).html('您还可以输入 <span class='+options.fontCls+'><strong>' + $_allowText + '</strong></span>');
                }
            };
            if (parseInt(maxlen, 10) > 0) {
                maxlen = parseInt(maxlen, 10);
                field.data('bindCheckFieldLength', true).bind('focus paste', function() {
                    setTimeout( function() {
                        checkLength();
                    }, 50);
                }).bind('keydown mousedown', function() {
                    if (tm != null) {
                        return true;
                    }
                    tm = setInterval(checkLength, 100);
                }).bind('keyup mouseup blur', function() {
                    clearInterval(tm);
                    tm = setTimeout( function() {
                        checkLength();
                    }, 50);
                });
            }

        });
    };
})(jQuery);
